package com.dyh.quickdemozwei.diffJs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.function.Function;

/**
 * @Author: yhdong
 * @Date: 2022/1/4 13:15
 */
public class JsDiff {

    public static void main(String[] args) {
        String str1 = "{\"s1\":\"t1v1\",\"j1\":{\"j1s1\":\"j1s1\",\"j1i1\":1},\"l1\":[{\"n1\":\"v1\"},{\"n2\":\"v2\"}]}";

        String str2 =
            "{\"s1\":\"t1v2\",\"s2\":\"t2v2\",\"j1\":{\"j1s1\":\"j1s2\",\"j1i1\":2},\"j2\":{\"j2s1\":\"j1s2\",\"j2i1\":2},\"l1\":[{\"n2\":\"v2\"},{\"n3\":\"v3\"}]}";


        JSONObject jo1 = JSON.parseObject(str1);
        JSONObject jo2 = JSON.parseObject(str2);

        String diffMsg = diff(jo2,jo1);

        System.out.println();
    }

    private static String diff(JSONObject newOne, JSONObject oldOne) {
        StringBuilder resultSb = new StringBuilder();
        for (Map.Entry<String, Object> entry : newOne.entrySet()) {
            String key = entry.getKey();

            if (newOne.get(key) instanceof JSONObject){
                resultSb.append(diff(newOne.getJSONObject(key),oldOne.getJSONObject(key)));
            }
            else {
                leafDiff(newOne, oldOne, resultSb, key);
            }
        }
        return resultSb.toString();
    }

    private static void leafDiff(JSONObject newOne, JSONObject oldOne, StringBuilder resultSb, String key) {
        String oldVal = oldOne==null||!oldOne.containsKey(key)?" ":oldOne.getString(key);
        String newVal = newOne.getString(key);
        resultSb.append("change ").append(key).append(":").append(oldVal).append("->")
                .append(newVal).append(";");
    }

    @Setter@Getter
    public static class EineDiff{
        String type;
        String field;
        String oldVal;
        String newVal;

    }
}
